package com.myself.pattern.factory.simplefactory;

import org.apache.commons.lang3.StringUtils;

import com.myself.pattern.factory.Bread;
import com.myself.pattern.factory.Cake;
import com.myself.pattern.factory.Food;

/**
 * #简单工程模式：所有食物都又一个工厂生产
 * 
 * @author 01055538
 *
 */
public class FoodFactory {

	/**
	 * #缺点： 每新增一种食物，就要增加一个 else if 分支
	 * 
	 * @param foodName 食物名称
	 * @return
	 */
	public static Food create(String foodName) {
		Food food = null;
		if ("bread".equals(foodName)) {
			food = new Bread();
		} else if ("cake".equals(foodName)) {
			food = new Cake();
		}
		// else if (...)
		return food;
	}

	/**
	 * #缺点： 对应食物的 java 全类名冗长复杂，且无法避免非法类名
	 * 
	 * @param className 对应食物的 java 全类名
	 * @return
	 */
	public static Food create2(String className) {
		Food food = null;
		try {
			if (StringUtils.isNotEmpty(className)) {
				food = (Food) Class.forName(className).newInstance();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return food;
	}

	public static Food create3(Class<? extends Food> clazz) {
		Food food = null;
		try {
			if (clazz != null) {
				food = clazz.newInstance();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return food;
	}

}
